
package com.netease.xone.fragment;

import java.util.LinkedList;

import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.XoneServiceCode;
import protocol.meta.LoopBack;
import protocol.meta.User;
import Utils.XoneUtil;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.UnderlineSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.netease.log.NTLog;
import com.netease.pkgRelated.XoneConsts;
import com.netease.share.ShareType;
import com.netease.xone.R;
import com.netease.xone.activity.ActivityCellPhoneLoginReg;
import com.netease.xone.activity.ActivityExternalLogin;
import com.netease.xone.dataMgr.MemoryDataCenter;
import com.netease.xone.widget.BadgeView;
import com.netease.xone.widget.CustomDialog.OnCustomDlgCancelListener;

import db.manager.ManagerAccount;
import db.manager.ManagerAccount.Account;

public class FragmentLogin extends FragmentBase {

    private static final String TAG = "FragmentLogin";

    public static final String NO_INI_PARAMS = "no_params";
    public static final String PARAMS_NAME = "name";
    public static final String PARAMS_PASSWORD = "password";
    public static final String PARAMS_LOGIN = "login";

    private AutoCompleteTextView mUserName;
    private EditText mPassWord;
    /** 登录按钮 */
    private TextView mBtnOk;
    /** 注册按钮 */
    private TextView mRegSubmit;

    private boolean mNoParams;

    private String mParamsName;
    private String mParamsPwd;
    private boolean mbParamsLogin;

    private boolean mbChecked = false;
    private BadgeView mBadgeView;
    private BadgeView mPwdBadgeView;
    private int mLoginTransId;
    private FrameLayout mSetNickView;
    private EditText mNickName;
    private TextView mSubmit;
    private boolean mBSwitchToMain = false;
    private int mGlobalErrCode = 0;

    private LinkedList<String> mAccountList = new LinkedList<String>();
    public static final String[] mDomain = new String[] {
            "@163.com", "@126.com", "@yeah.net", "@qq.com", "@vip.163.com", "@vip.126.com",
            "@188.com", "@gmail.com", "@sina.com", "@hotmail.com"
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        View view = inflater.inflate(R.layout.fragment_login, container, false);
        findViews(view);
        iniViews();

        if (mbParamsLogin) {
            mBtnOk.performClick();
        }
        return view;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        XoneService.getInstance().addListener(mXoneCallBack);
        Intent intent = getActivity().getIntent();
        if(intent != null){
            mBSwitchToMain = intent.getBooleanExtra(XoneConsts.BUNDLE_KEY.SWITCH_TO_MAIN, false);
            mGlobalErrCode = intent.getIntExtra(XoneConsts.BUNDLE_KEY.SWITCH_TO_LOGIN_ERRCODE, 0);
            NTLog.v(TAG, "onCreate + mGlobalErrCode " + mGlobalErrCode);
        }
    }
    private void findViews(View view) {
        mUserName = (AutoCompleteTextView)view.findViewById(R.id.UserName);
        mPassWord = (EditText)view.findViewById(R.id.PassWord);
        mBtnOk = (TextView)view.findViewById(R.id.Login);
        mRegSubmit = (TextView)view.findViewById(R.id.regSubmit);
        mSetNickView = (FrameLayout)view.findViewById(R.id.set_nickname);
        mNickName = (EditText)view.findViewById(R.id.editNickNameInput);
        mSubmit = (TextView)view.findViewById(R.id.Submit);

        mUserName.setThreshold(1);
        mUserName.addTextChangedListener(mNameChanged);

        mBadgeView = new BadgeView(getActivity(), mUserName);
        // mBadgeView.setLayoutParams(new LinearLayout.LayoutParams(0,
        // LayoutParams.WRAP_CONTENT, 1));
        mBadgeView.setBackgroundDrawable(getActivity().getResources().getDrawable(
                R.drawable.text_del));
        mBadgeView.setBadgePosition(BadgeView.POSITION_CENTER_VERTICAL_RIGHT);
        mBadgeView.setBadgeMargin(XoneUtil.dip2px(getActivity(), 3));
        mBadgeView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mUserName.setText("");
            }
        });
        mUserName.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    mBadgeView.hide();
                } else {
                    mUserName.setText(mUserName.getEditableText().toString());
                    mUserName.setSelection(mUserName.getEditableText().toString().length());
                }
            }
        });

        mPwdBadgeView = new BadgeView(getActivity(), mPassWord);
        // mBadgeView.setLayoutParams(new LinearLayout.LayoutParams(0,
        // LayoutParams.WRAP_CONTENT, 1));
        mPwdBadgeView.setBackgroundDrawable(getActivity().getResources().getDrawable(
                R.drawable.text_del));
        mPwdBadgeView.setBadgePosition(BadgeView.POSITION_CENTER_VERTICAL_RIGHT);
        mPwdBadgeView.setBadgeMargin(XoneUtil.dip2px(getActivity(), 3));
        mPwdBadgeView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mPassWord.setText("");
            }
        });
        mPassWord.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 0) {
                    mPwdBadgeView.hide();
                } else {
                    mPwdBadgeView.show();
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
        });
        mPassWord.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    mPwdBadgeView.hide();
                } else {
                    mPassWord.setText(mPassWord.getEditableText().toString());
                    mPassWord.setSelection(mPassWord.getEditableText().toString().length());
                }
            }
        });

        mRegSubmit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse("http://reg.163.com/reg/regClient.jsp?product=easyread");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });

        mBtnOk.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                doLogin();
            }
        });

        TextView forgotPassword = (TextView)view.findViewById(R.id.loginForgotPassword);
        SpannableString ss = new SpannableString(getString(R.string.forgetPassword));
        ss.setSpan(new UnderlineSpan(), 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        forgotPassword.setText(ss);
        forgotPassword.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse("http://reg.163.com/getpasswd/RetakePassword.jsp");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
        // 其它方式登录
        LinearLayout lay = (LinearLayout)view.findViewById(R.id.loginCellPhone);// cellphone
        lay.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ActivityCellPhoneLoginReg.launch(getActivity());
            }
        });
        lay = (LinearLayout)view.findViewById(R.id.loginSina);// sina
        lay.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ActivityExternalLogin.launch(getActivity(), ShareType.Sina.value());
            }
        });
        lay = (LinearLayout)view.findViewById(R.id.loginQq);// qq
        lay.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ActivityExternalLogin.launch(getActivity(), ShareType.Qqmblog.value());
            }
        });
        lay = (LinearLayout)view.findViewById(R.id.loginRenren);// renren
        lay.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ActivityExternalLogin.launch(getActivity(), ShareType.Renren.value());

            }
        });

        // 设置昵称
        mNickName.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    return;
                }
                int len = 0;
                for (int i = 0; i < s.length(); i++) {
                    String ss = Character.toString(s.charAt(i));
                    if (ss.matches("[\\u4E00-\\u9FA5]")) {
                        len += 2;
                    } else {
                        len++;
                    }
                    if (len > getActivity().getResources().getInteger(R.integer.nicknameMaxLen)) {
                        showToast(R.string.textNumExceedLimit);
                        String sss = s.subSequence(0, i).toString();
                        mNickName.setText(sss);
                        mNickName.setSelection(sss.length());
                        break;
                    }
                }
                // String nickname = mNickName.getText().toString().trim();
            }
        });
        mSubmit.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                doUrsReg();
            }
        });
        if(mGlobalErrCode >0 ){
            new Handler().postDelayed(mMyRunnable, 500);
        }
//        showCustomDialog(getActivity(), "测试测试测试测试", null);
    }
    private OnCustomDlgCancelListener mOnCustomDlgCancelListener = new OnCustomDlgCancelListener(){

        @Override
        public void onCancel() {
            NTLog.v(TAG, "onCancel");
            XoneService.getInstance().cancelTransaction(mLoginTransId);
        }  
    };
  //处理全局的帐号异常
    private Runnable mMyRunnable = new Runnable() {
        @Override
        public void run() {
            if (MemoryDataCenter.getInstance().get(XoneConsts.MEMORY_ACC_DELETE_TAG) == null) {
                ManagerAccount.getInstance().deleteAccountByUserId(
                        ManagerAccount.getInstance().getCurrentAccountId());
            } else {
                MemoryDataCenter.getInstance().remove(XoneConsts.MEMORY_ACC_DELETE_TAG);
            }
            int resId = 0;
            if(mGlobalErrCode == XoneServiceCode.LOGINREG_ERR_USER_LOCKED){
                resId = R.string.accexption_locked;
            } else {
                resId = R.string.accexption_acc_pw_error;
            }
            
            new AlertDialog.Builder(getActivity())
            .setTitle(R.string.tip)
            .setMessage(resId)
            .setPositiveButton(R.string.sure,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(
                                DialogInterface dialoginterface, int j) {
                        }
                    }).show();            
        } 
    };

    private boolean isNumber(String s) {
        if (s == null)
            return false;

        if (s.startsWith("1")) {
            for (int i = 0; i < s.length(); i++) {
                char d = s.charAt(i);
                if (d < '0' || d > '9') {
                    return false;
                }
            }
            return true;
        }

        return false;
    }

    private TextWatcher mNameChanged = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            mAccountList.clear();
            String typeInText = s.toString();

            if (typeInText.indexOf("@") == -1) {
                if (isNumber(typeInText))
                    mAccountList.add(typeInText);

                for (String str : mDomain)
                    mAccountList.add(typeInText + str);
            } else {
                if (typeInText.indexOf(typeInText.length() - 1) == '@') {
                    for (String str : mDomain)
                        mAccountList.add(typeInText + str);
                } else {
                    int index = typeInText.indexOf("@");
                    String domainPart = typeInText.substring(index + 1);
                    String usernamePart = typeInText.substring(0, index);
                    for (String str : mDomain) {
                        if (str.indexOf(domainPart) != -1)
                            mAccountList.add(usernamePart + str);
                    }
                }
            }
            ArrayAdapter<String> mAccountAdapter = new ArrayAdapter<String>(getActivity(),
                    R.layout.dropdown_item, mAccountList);
            mUserName.setAdapter(mAccountAdapter);
            mUserName.invalidate();
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.toString().length() == 0) {
                mBadgeView.hide();
            } else {
                mBadgeView.show();
            }
        }
    };

    private void iniViews() {
        if (mNoParams)
            return;

        if (!TextUtils.isEmpty(mParamsName)) {
            mUserName.setText(mParamsName);
            mPassWord.setText(mParamsPwd);
            return;
        }
        // AccountInfo account =
        // WbAccMgr.getInstance(this).getLastLoninAccount();
        // if(account != null){
        // String user = account.accout;
        // if(!TextUtils.isEmpty(user))
        // mUserName.setText(user);
        //
        // boolean bSave = account.bSavePwd;
        // String pwd = account.pwd;
        // if(bSave && !TextUtils.isEmpty(pwd)){
        // mPassWord.setText(pwd);
        // }
        //
        // }
    }

    @Override
    public void onResume() {
        super.onResume();
        getActivity().setTitle(R.string.login);
    }

    private void switchToEditNickName() {
        if (mSetNickView.getVisibility() != View.VISIBLE) {
            mSetNickView.setVisibility(View.VISIBLE);
            mNickName.setText("");
            getActivity().setTitle(R.string.nicknamSet);
        }
    }
    public boolean onBack(){
        boolean res = false;
        if (mSetNickView.getVisibility() != View.GONE) {
            mSetNickView.setVisibility(View.GONE);
            getActivity().setTitle(R.string.login);
            res = true;
        }
        if(!res && mGlobalErrCode >0){
            processAccException();
            res = true;
        }
        return res;
    }
    public boolean processAccException(){
        boolean res = false;
        final Account acc = ManagerAccount.getInstance()
              .getNewestAccount();
      if (acc != null) {
          new AlertDialog.Builder(getActivity())
          .setTitle(R.string.tip)
          .setMessage(R.string.accexption_switch)
          .setPositiveButton(R.string.sure,
                  new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(
                              DialogInterface dialoginterface, int j) {
//                          showWatting(acc.mNickName + "" +getString(R.string.logining));
                          showCustomDialog(getActivity(),acc.mNickName + "" +getString(R.string.logining),mOnCustomDlgCancelListener);
                          mLoginTransId = XoneService.getInstance().doLogin(acc.mUserType,
                                  acc.mUserName, acc.mPassword);
                      }
                  }).setCancelable(false).show(); 
      } else {
//        showWatting("游客" + "" +getString(R.string.logining));
        showCustomDialog(getActivity(),"游客" + "" +getString(R.string.logining),mOnCustomDlgCancelListener);
        mLoginTransId = XoneService.getInstance().doAnomyousLogin();
      }  
      return res;
    }
    @Override
    protected void onLeftTopBack() {
       if(!onBack()){
           getActivity().finish();
       }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        XoneService.getInstance().removeListener(mXoneCallBack);
    }
    private void doLogin() {
        String user = mUserName.getText().toString().trim();
        String pwd = mPassWord.getText().toString();

        if (TextUtils.isEmpty(user)) {
            showToast(R.string.input_user_name);
            return;
        }
        if (TextUtils.isEmpty(pwd)) {
            showToast(R.string.input_password);
            return;
        }
//        showWatting(getString(R.string.logining));
        showCustomDialog(getActivity(),getString(R.string.logining),mOnCustomDlgCancelListener);
        mLoginTransId = XoneService.getInstance().doLogin(XoneConsts.ACCOUNT_TYPE.Urs,
                user, pwd);
    }
    private void doUrsReg(){
        String nicknameStr = mNickName.getText().toString().trim();
        int msgid = -1;
        if (TextUtils.isEmpty(nicknameStr)) {
            msgid = R.string.inputNicknamePrompt;
        }  else if (XoneUtil.getNicknameLen(nicknameStr) < getActivity().getResources().getInteger(R.integer.nicknameMinLen)) {
            msgid = R.string.nicknameLenUnreachFour;
        } else if (XoneUtil.getNicknameLen(nicknameStr) > getActivity().getResources().getInteger(R.integer.nicknameMaxLen)) {
            msgid = R.string.nicknameLenOverCeiling;
        } else if (XoneUtil.isNicknameContainsSpecialChar(nicknameStr)) {
            msgid = R.string.nicknameContainsSpecialChar;
        }  
        if(msgid > 0){
            showToast(msgid);
            return;
        }
        String user = mUserName.getText().toString().trim();
        String pwd = mPassWord.getText().toString();
        mLoginTransId = XoneService.getInstance().doUrsUserReg(user, pwd, nicknameStr);
//        showWatting(getString(R.string.registering));
        showCustomDialog(getActivity(),getString(R.string.registering),mOnCustomDlgCancelListener);
        
        
        
    }
    private XoneCallBack mXoneCallBack = new XoneCallBack() {

        @Override
        public void onLogin(int transactionId, User account) {
            NTLog.v(TAG, "onLogin + " + account);
//            showToast("loginseucess " + account);
//            stopWaiting();
            closeCustomDialog();
            LoopBack lb = new LoopBack();
            lb.mType = XoneConsts.LOOPBACK_TYPE.switch_account;
            if(mBSwitchToMain){
                lb.mData = new Boolean(true);
            } else {
                lb.mData = new Boolean(false);
            }
            XoneService.getInstance().doLoopBack(lb);
            getActivity().finish();
        }

        @Override
        public void onLoginError(int transactionId, int errCode, String err) {
            if (mLoginTransId == transactionId) {
                closeCustomDialog();
                LoopBack lb = new LoopBack();
                if (XoneServiceCode.LOGINREG_ERR_NICKNAME_EXIST == errCode) {
                    switchToEditNickName();
                } else {
                    showToast(err);
//                    getActivity().finish();
                }
            }

        }
    };
    
}
